package com.hn658.groupshare.backend.action.user.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.hn658.framework.common.AbstractBaseService;
import com.hn658.framework.common.IServiceResponse;
import com.hn658.framework.dataaccess.pagination.GenericPage;
import com.hn658.framework.shared.context.UserContext;
import com.hn658.framework.shared.exception.BusinessException;
import com.hn658.groupshare.backend.action.role.vo.RoleInfoResponse;
import com.hn658.groupshare.backend.action.user.IUserAction;
import com.hn658.groupshare.backend.action.user.vo.CurrentUserResponse;
import com.hn658.groupshare.backend.action.user.vo.QueryUserResponse;
import com.hn658.groupshare.backend.action.user.vo.UserRequest;
import com.hn658.groupshare.common.entity.RoleInfoEO;
import com.hn658.groupshare.common.entity.TreeNode;
import com.hn658.groupshare.common.entity.UserInfoEO;
import com.hn658.groupshare.common.expection.UserException;
import com.hn658.groupshare.common.vo.CommonRequest;
import com.hn658.groupshare.common.vo.CommonResponse;
import com.hn658.groupshare.core.service.IUserInfoService;


@Controller("userAction")
@Path("user")
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")
public class UserAction extends AbstractBaseService implements IUserAction {

	@Autowired
	private IUserInfoService userInfoService;
	
	//@Autowired
	//private IFileManager fileManager;

	/**
	 * 查询用户列表
	 * 
	 * @return
	 */
	@Path("queryUser")
	@Consumes("application/x-www-form-urlencoded; charset=UTF-8")
	@Produces("application/json; charset=UTF-8")
	@POST
	public IServiceResponse queryUser(
			@FormParam("loginAccount") String loginAccount,
			@FormParam("isDeleted") String isDeleted,
			@FormParam("nickName") String nickName,
			@FormParam("realName") String realName,
			@FormParam(value="limit") int limit, 
			@FormParam(value="start") int start) {

		Map<String, Object> queryMap = new HashMap<String, Object>();
		QueryUserResponse resp = new QueryUserResponse();
		
		if(StringUtils.isNotBlank(isDeleted)){
			queryMap.put("isDeleted", Boolean.parseBoolean(isDeleted));
		}
		if (StringUtils.isNotBlank(loginAccount)) {
			queryMap.put("loginAccount", loginAccount.trim());
		}
		if (StringUtils.isNotBlank(nickName)) {
			queryMap.put("nickName", nickName.trim());
		}
		if (StringUtils.isNotBlank(realName)) {
			queryMap.put("realName", realName.trim());
		}
		GenericPage<UserInfoEO> genericPage = userInfoService.queryUser(
				queryMap, limit, start, null, true);
		resp.getUserList().addAll(genericPage.getData());
		resp.setTotalCount(genericPage.getTotalCount());
		this.success(resp);

		return resp;
	}
	
	@Path("queryAllUser")
	@Consumes("application/x-www-form-urlencoded; charset=UTF-8")
	@Produces("application/json; charset=UTF-8")
	@POST
	public IServiceResponse queryAllUser() {
		Map<String, Object> queryMap = new HashMap<String, Object>();
		QueryUserResponse resp = new QueryUserResponse();
		queryMap.put("isDeleted", false);
		List<UserInfoEO> genericPage = userInfoService.queryAllUser(queryMap);
		resp.setUserList(genericPage);
		this.success(resp);
		return resp;
	}
    
	@Path("queryAuthedRoles")
	@Consumes("application/x-www-form-urlencoded; charset=UTF-8")
	@Produces("application/json; charset=UTF-8")
	@POST
	public IServiceResponse queryAuthedRoles(@FormParam(value="uid") Long uid) {
		RoleInfoResponse response = new RoleInfoResponse();
		try {
			List<RoleInfoEO> roleInfoList = userInfoService.queryAuthedRoles(uid);
			response.setRoleInfoList(roleInfoList);
			this.success(response);
        } catch (BusinessException e) {
            this.error(response, e);
        }
		return response;
	}
	
    
    @Path("queryUnAuthedRoles")
    @Consumes("application/x-www-form-urlencoded; charset=UTF-8")
    @Produces("application/json; charset=UTF-8")
    @POST
    public IServiceResponse queryUnAuthedRoles(@FormParam(value="uid") Long uid) {
    	RoleInfoResponse response = new RoleInfoResponse();
        try {
            List<RoleInfoEO> roleInfoList = userInfoService.queryUnAuthedRoles(uid);
            response.setRoleInfoList(roleInfoList);
            this.success(response);
        } catch (BusinessException e) {
            this.error(response, e);
        }
        return response;
    }
    
    @Path("authUserRoles")
	@POST
	public IServiceResponse authUserRoles(UserRequest request) {
    	CommonResponse response = new CommonResponse();
        try {
            userInfoService.authUserRoles(request.getId(), request.getRoleIds());
            this.success(response);
        } catch (BusinessException e) {
            this.error(response, e);
        }
        return response;
	}

	@Path("currentUserInfo")
	@POST
	public IServiceResponse currentUserInfo(CommonRequest request) {
		UserInfoEO userInfo = (UserInfoEO)UserContext.getCurrentUser();
		CurrentUserResponse cur = new CurrentUserResponse();
		cur.setUserInfo(userInfo);
		List<TreeNode> treeNodes = userInfoService.queryUserTreeNodes(userInfo.getId());
		cur.setTreeNodes(treeNodes);
		this.success(cur);
		return cur;
	}

	@Path("addUser")
	@Consumes("multipart/form-data; charset=UTF-8")
	@POST
	public IServiceResponse addUser(
			@Multipart(value = "loginAccount", required = true) String loginAccount,
			@Multipart(value = "password", required = true) String password,
			@Multipart(value = "sex", required = false) String sex,
			@Multipart(value = "realName", required = true) String realName,
			@Multipart(value = "nickName", required = true) String nickName,
			@Multipart(value = "qq", required = false) String qq,
			@Multipart(value = "weiXin", required = false) String weiXin,
			@Multipart(value = "phoneNumber", required = false) String phoneNumber,
			@Multipart(value = "sign", required = false) String sign,
			@Multipart(value = "avatarUrl", required = false) byte[] file,
			@Context HttpServletRequest request) {
		CommonResponse response=new CommonResponse();
		try{
			UserInfoEO uie = new UserInfoEO();
			uie.setLoginAccount(loginAccount);
			uie.setPassword(password);
			if (!"".equals(sex) && sex != null) {
				uie.setSex(sex);
			}
			uie.setRealName(realName);
			uie.setNickName(nickName);
			if (!"".equals(qq) && qq != null) {
				uie.setQq(qq);
			}
			if (!"".equals(weiXin) && weiXin != null) {
				uie.setWeiXin(weiXin);
			}
			if (!"".equals(phoneNumber) && phoneNumber != null) {
				uie.setPhoneNumber(phoneNumber);
			}
			if (!"".equals(sign) && sign != null) {
				uie.setSign(sign);
			}
			userInfoService.addUser(uie);
			if(file!=null&&file.length>0){
				//String[] uris = fileManager.saveAvatar(file, uie.getId().toString());
				//uie.setAvatarUrl(uris[0]);			
			}
			userInfoService.modifyUserInfo(uie);
			this.success(response);
		}catch (BusinessException e) {
			this.error(response, e);
		}
		return response;
	}
	
	
	/**
	 * 修改后台管理用户
	 * @return
	 * @throws IOException 
	 */
	@Path("modifyUser")
	@Consumes("multipart/form-data; charset=UTF-8")
	@POST
	public IServiceResponse modifyUser(
			@Multipart(value = "id", required = true) String id,
			@Multipart(value = "loginAccount", required = true) String loginAccount,
			@Multipart(value = "password", required = true) String password,
			@Multipart(value = "sex", required = false) String sex,
			@Multipart(value = "realName", required = true) String realName,
			@Multipart(value = "nickName", required = true) String nickName,
			@Multipart(value = "qq", required = false) String qq,
			@Multipart(value = "weiXin", required = false) String weiXin,
			@Multipart(value = "phoneNumber", required = false) String phoneNumber,
			@Multipart(value = "sign", required = false) String sign,
			@Multipart(value = "avatarUrl", required = false) byte[] file,
			@Context HttpServletRequest request){
		CurrentUserResponse response = new CurrentUserResponse();
		try{
			UserInfoEO uie = new UserInfoEO();
			uie.setId(Long.valueOf(id));
			uie.setLoginAccount(loginAccount);
			uie.setPassword(password);
			uie.setId(Long.valueOf(id));
			if (!"".equals(sex) && sex != null) {
				uie.setSex(sex);
			}
			uie.setRealName(realName);
			uie.setNickName(nickName);
			if (!"".equals(qq) && qq != null) {
				uie.setQq(qq.trim());
			}
			if (!"".equals(weiXin) && weiXin != null) {
				uie.setWeiXin(weiXin.trim());
			}
			if (!"".equals(phoneNumber) && phoneNumber != null) {
				uie.setPhoneNumber(phoneNumber.trim());
			}
			if (!"".equals(sign) && sign != null) {
				uie.setSign(sign.trim());
			}
			
			if(file!=null&&file.length>0){
				//String[] uris = fileManager.saveAvatar(file, uie.getId().toString());
				//uie.setAvatarUrl(uris[0]);			
			}
			uie = userInfoService.modifyUserInfo(uie);
			response.setUserInfo(uie);
			this.success(response);
		}catch (BusinessException e) {
			this.error(response, e);
		}
		return response;
	}
	
	@Path("enableUser")
	@Consumes("application/x-www-form-urlencoded; charset=UTF-8")
	@POST
	public IServiceResponse enableUser(@FormParam("id") String id) {
		CommonResponse response=new CommonResponse();
		try{
			if (StringUtils.isBlank(id)) {
				throw new UserException(UserException.UserIdEmptyWrong);
			}
			userInfoService.enableUser(Long.valueOf(id));
			this.success(response);
		}catch (BusinessException e) {
			this.error(response, e);
		}
		return response;
	}
	
	/**
	 * 禁用用户
	 * @return
	 */
	@Path("disableUser")
	@Consumes("application/x-www-form-urlencoded; charset=UTF-8")
	@POST
	public IServiceResponse disableUser(@FormParam("id") String id) {
		CommonResponse response=new CommonResponse();
		try{
			if (StringUtils.isBlank(id)) {
				throw new UserException(UserException.UserIdEmptyWrong);
			}
			userInfoService.disableUser(Long.valueOf(id));
			this.success(response);
		}catch (BusinessException e) {
			this.error(response, e);
		}
		this.success(response);
		return response;
	}

	@Path("modifyPassWord")
	@Consumes("application/x-www-form-urlencoded; charset=UTF-8")
	@POST
	public IServiceResponse modifyPass(
			@FormParam("oldPass") String oldPass,
			@FormParam("newPass") String newPass,
            @FormParam("loginAccount") String loginAccount) {
		CommonResponse comres=new CommonResponse();
		try {
            boolean isreset  = false;
            UserInfoEO changeUser = (UserInfoEO) UserContext.getCurrentUser();
			if(StringUtils.isNotEmpty(loginAccount)){
                UserInfoEO userInfo = userInfoService.findUserByAccount(loginAccount);
                changeUser = userInfo;
                isreset = true;
            }
			userInfoService.modifyCurrentUserPassword(changeUser, oldPass, newPass,isreset);
			
			this.success(comres);
		} catch (BusinessException e) {
			this.error(comres, e);
		}

		return comres;
	}
}
